import Vue from "vue";
import "./extend";
import helper from "./helper";
// import file from "./file";

const $vue = Vue.prototype;

for (const fn in helper) {
  $vue["$" + fn] = helper[fn];
}
// $vue.$file = file;

$vue.$inH5 = false;
$vue.$inWx = false;
$vue.$inMp = false;
$vue.$inMpWx = false;

// #ifdef H5
$vue.$inH5 = true;
$vue.$inWx = /micromessenger/i.test(navigator.userAgent);
$vue.$inDev = /localhost/.test(location.host);
// #endif

// #ifdef APP
$vue.$inApp = true;
// #endif

// #ifdef MP
$vue.$inMp = true;
// #endif

// #ifdef MP-WEIXIN
$vue.$inMpWx = true;
// #endif

// https://uniapp.dcloud.io/api/README?id=路由
export const navTo = (url, act = "navigateTo", params = {}) => {
  if (typeof act == "object" && act) {
    params = act;
    act = "navigateTo";
  }
  if (/^https:/.test(url)) {
    params.src = url;
    url = "/pages/webview/webview";
  } else if (/^[a-z]/.test(url) && !url.includes("plugin:")) {
    if (/\//.test(url)) url = `/pages/${url}`;
    else url = `/pages/${url}/${url}`;
  }

  for (const key in params) {
    let val = params[key];
    if (val === undefined) continue;
    if (val && typeof val == "object") val = JSON.stringify(val);
    if (val) val = encodeURIComponent(val);
    const add = /\?/.test(url) ? "&" : "?";
    url += `${add}${key}=${val}`;
  }
  uni[act]({
    url,
  });
};
$vue.$navTo = navTo;
["redirectTo", "reLaunch", "switchTab"].forEach((act) => {
  $vue["$" + act] = (url, params) => {
    navTo(url, act, params);
  };
});

$vue.$onScan = async () => {
  const {
    result
  } = await helper.scanCode();
  const val = result.trim();
  if (!val) return $vue.$toast("未识别类型");
  navTo("preview/text", {
    input: val,
    from: "scan",
  });
};

$vue.$navBack = () => {
  if (getCurrentPages().length == 1) navTo("index", "reLaunch");
  else uni.navigateBack();
};